<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head th:replace="back/include :: header">
</head>
<body>
<form class="layui-form" id="searchForm">
    <div class="layui-row" style="text-align: center">
        <div class="layui-col-md12" style="padding:20px;">
            登录名称：
            <div class="layui-inline">
                <input class="layui-input" name="loginName" id="loginName" autocomplete="off">
            </div>
            手机号码：
            <div class="layui-inline">
                <input class="layui-input" name="phonenumber" id="phonenumber" autocomplete="off">
            </div>
            用户状态：
            <div class="layui-inline">
                <select name="status" lay-filter="status" id="status">
                    <option value="" selected>全部</option>
                    <option value="0">正常</option>
                    <option value="1">停用</option>
                </select>
            </div>
            创建时间：
            <div class="layui-inline">
                <input type="text" class="layui-input" name="startTime" id="startTime" placeholder="开始时间"
                       onfocus="noInput(this)">
            </div>
            -
            <div class="layui-inline">
                <input type="text" class="layui-input" name="endTime" id="endTime" placeholder="截止时间"
                       onfocus="noInput(this)">
            </div>
            <div class="layui-inline" style="float:right;">
                <button shiro:hasPermission="system:sysUser:list"  type="button" class="layui-btn" data-type="reload" id="search">搜索</button>
                <button shiro:hasPermission="system:sysUser:list"  type="button" class="layui-btn layui-btn-primary" data-type="reload" id="clear">重置</button>
                <button shiro:hasPermission="system:sysUser:add" type="button" class="layui-btn" data-type="reload" id="add"><i class="layui-icon">&#xe608;</i>新增
                </button>
            </div>
        </div>
    </div>
</form>
<table class="layui-hide" id="demoTable" lay-filter="tableFilter"></table>

<!--弹出框-->
<form class="layui-form layui-form-pane" id="sysUserInfo" style="display:none">
    <input type="hidden" name="userId" id="_userId">
    <div class="layui-form-item" style="padding-top: 10px">
        <label class="layui-form-label is-required">用户名称</label>
        <div class="layui-input-block">
            <input type="text" name="userName" id="_userName" lay-verify="required|username" placeholder="请输入登录名称"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label is-required">手机号码</label>
        <div class="layui-input-block">
            <input type="text" name="phonenumber" id="_phonenumber" lay-verify="required|phone" placeholder="请输入手机号码"
                   class="layui-input required">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label is-required">登录名称</label>
        <div class="layui-input-block">
            <input type="text" name="loginName" id="_loginName"  lay-verify="required|username"
                   placeholder="请输入登录名称" class="layui-input required">
        </div>
    </div>
    <div class="layui-form-item" id="_pass">
        <label class="layui-form-label is-required">登录密码</label>
        <div class="layui-input-block">
            <input type="password" name="password" id="_password"  lay-verify="required|pass"
                   placeholder="请输入登录密码" class="layui-input required">
        </div>
    </div>
    <div class="layui-form-item ">
        <label class="layui-form-label">用户性别</label>
        <div class="layui-input-block">
            <select name="sex" id="_sex">
                <option value="0" selected>男</option>
                <option value="1">女</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" id="_email" placeholder="请输入邮箱"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户状态</label>
        <div class="layui-input-block">
            <input type="checkbox" id="_status" name="status" lay-skin="switch" checked>
        </div>
    </div>
</form>
<form class="layui-form layui-form-pane" id="reset" style="display:none">
    <input type="hidden" name="userId" id="_resetUserId">
    <div class="layui-form-item">
        <label class="layui-form-label">登录名称</label>
        <div class="layui-input-block">
            <input type="text" id="_userLoginName" readonly class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label is-required">新密码</label>
        <div class="layui-input-block">
            <input type="password" name="password" id="_newPassword" lay-verify="required|pass" placeholder="请输入登录密码"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label is-required">再次输入</label>
        <div class="layui-input-block">
            <input type="password" id="_repeatPassword" name="passRepeat" lay-verify="required|pass" placeholder="请输入登录密码"
                   class="layui-input">
        </div>
    </div>
</form>
<script type="text/javascript">
    let tableIns;
    //加载下拉框
    layui.use(['laydate', 'laypage', 'layer', 'table', 'form'], function () {
        let layer = layui.layer //弹层
            , table = layui.table //表格
            , form = layui.form,
            laydate = layui.laydate; //元素操作
        //执行一个 table 实例
        table.render({
            elem: '#demoTable'
            , url: '/back/sysUser/list'
            , method: 'post'
            , contentType: 'application/json'
            , id: 'demoTable'
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
            , where: {}
            , response: {
                statusCode: 1 //规定成功的状态码，默认：0
            }
            , page: true //开启分页
            , cols: [
                [
                    /*{type:'checkbox'}*/
                    /*   ,{title: '序号', type:'numbers', align: 'center'}*/
                    {width: '6%', field: 'userId', title: '用户编号', align: 'center'}
                    , {field: 'loginName', title: '登录名称', align: 'center'}
                    , {field: 'userName', title: '用户昵称', align: 'center'}
                    , {field: 'phonenumber', title: '手机号码', align: 'center'}
                    , {field: 'status', title: '用户状态', align: 'center', templet: '#checkboxS'}
                    , {
                    field: 'createTime', title: '创建时间', align: 'center', templet: function (d) {
                        return layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss");
                    }
                }
                    , {width: '15%', title: '操作', align: 'center', toolbar: '#bar'}
                ]
            ]
        });
        //常规用法
        laydate.render({
            elem: '#startTime'
            , trigger: 'click'
        });
        laydate.render({
            elem: '#endTime'
            , trigger: 'click'
        });
        form.verify({
            username: function (value, item) { //value：表单的值、item：表单的DOM对象
                if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                    return '名称不能有特殊字符';
                }
                if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                    return '名称首尾不能出现下划线\'_\'';
                }
                if (/^\d+\d+\d$/.test(value)) {
                    return '名称不能全为数字';
                }
                if (value.length < 2) {
                    return '名称不得少于两个字符';
                }
            }

            //我们既支持上述函数式的方式，也支持下述数组的形式
            //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
            , pass: [/^[\S]{5,12}$/, '密码必须5到12位，且不能出现空格']

        });
        $("#add").bind("click", function () {
            $("#sysUserInfo").clearForm();
            $("#_userId").val("");
            $("#_loginName").removeAttr("readonly");
            $('#_password').prop("lay-verify","required|pass");
            $('#_pass').show();
            openLayer('新建管理员', '/back/sysUser/add', 0);
        });

        $("#search").bind("click", function () {
            searchForm();
        });

        $("#clear").bind("click", function () {
            $("#searchForm").clearForm();
            searchForm();
        });
        form.on('switch(release)', function (obj) {
            let data = {userId: obj.value, status: obj.elem.checked ? 0 : 1}
            saveData("/back/sysUser/update", data);
            searchForm();
        });
        /*ESC关闭弹窗*/
        $(document).ready(function () {
        }).keydown(
            function (e) {
                if (e.which === 27) {
                    layer.closeAll();
                }
            });

        form.on('select(status)', function (data) {
            searchForm();
        });
        form.on('submit(formDemo)', function (data) {
            //layer.msg(JSON.stringify(data.field));
            return false;
        });
        table.on('tool(tableFilter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            let data = obj.data; //获得当前行数据
            let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if (layEvent === 'edit') { //编辑
                $('#_pass').hide();
                $("#_password").removeAttr("lay-verify");
                getEditData(data['userId']);
                openLayer('编辑管理员信息', '/back/sysUser/update', 1);
            } else if (layEvent === 'del') { //删除
                layer.confirm('确认要删除吗', {icon: 3, title: '信息删除确认'}, function (index) {
                    saveData("/back/sysUser/del", {userId: data['userId']});
                });
            } else if (layEvent === 'reset') {
                reset(data['userId'], data['loginName']);
            }
        });


        function reset(userId, loginName) {
            $("#reset").clearForm();
            $("#_resetUserId").val(userId);
            $("#_userLoginName").val(loginName);
            layer.open({
                type: 1,
                area: ['600px', '300px'],
                title: "重置密码"
                , content: $("#reset"),
                shade: 0.3,
                resize: false,
                moveType: 1,//可拖动
                moveOut: true,//可拖动移出
                shadeClose: true,//点击遮罩关闭弹窗
                btn: ['重置', '返回']
                ,
                success: function (layero, index) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0 ').attr('lay-filter', 'formVerify')
                        .attr('lay-submit', '');
                    form.render();
                },
                yes: function (layero, index) {
                    form.on('submit(formVerify)', function (obj) {
                        let data = obj.field;
                        if(data.passRepeat!=data.password){
                            layer.alert("两次密码输入不一致");
                            return false;
                        }
                        delete data['passRepeat'];
                        saveData("/back/sysUser/reset", data);
                        return false;
                    });
                }
                ,
                btn2: function (index, layero) {
                    layer.closeAll();
                },
                cancel: function (layero, index) {
                    layer.closeAll();
                }
            });
        }
        function saveData(url, data) {
            $.ajax({
                type: "post",
                url: url,
                data: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                dataType: 'json',
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status + "," + XMLHttpRequest.readyState + ","
                        + textStatus + "," + errorThrown);
                },
                success: function (result) {
                    if (result["status"] == 1) {
                        layer.closeAll();
                        layer.msg(result["msg"]);
                        searchForm();
                    } else {
                        layer.alert(result['msg']);
                    }
                }
            });
        }

        function getEditData(data) {
            //获取行
            /*layui.use('table', function(){
            let table = layui.table;
            let checkData = table.checkStatus('demoTable').data;
           if(checkData.length != 1){
                layer.msg('请选择一行数据！');
                return;
           }
           let id = checkData[0]["id"];*/
            $("#sysUserInfo").clearForm();
            $.ajax({
                type: "post",
                url: "/back/sysUser/getUserInfo",
                data: JSON.stringify({"userId": data}),
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                dataType: 'json',
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status + "," + XMLHttpRequest.readyState + ","
                        + textStatus + "," + errorThrown);
                },
                success: function (result) {
                    if (result['status'] == 1) {
                        let data = result["data"];
                        $("#_userId").val(data["userId"]);
                        $("#_loginName").val(data["loginName"]);
                        $("#_loginName").attr("readonly", "readonly");
                        $("#_phonenumber").val(data["phonenumber"]);
                        $("#_userName").val(data["userName"]);
                        $("#_email").val(data["email"]);
                        let sex = data['sex'];
                        let status = data['status'];
                        $("#_sex").val(sex);
                        if (status == 0) {
                            $("#_status").prop('checked', true);
                        } else {
                            $("#_status").removeAttr('checked');
                        }
                        layui.use(['form'], function () {
                            layui.form.render("checkbox");
                            layui.form.render("select");
                        });
                    } else {
                        layui.alert(result['msg']);
                    }
                }
            });
        }

        function openLayer(titleName, url, type) {
            //type  0新增  1编辑
            layer.open({
                type: 1,
                area: ['800px', '480px'],
                title: titleName
                , content: $("#sysUserInfo"),
                shade: 0.3,
                resize: false,
                moveType: 1,//可拖动
                moveOut: true,//可拖动移出
                shadeClose: true,//点击遮罩关闭弹窗
                btn: ['提交', '返回'],
                success: function (layero, index) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0 ').attr('lay-filter', 'formVerify')
                        .attr('lay-submit', '');
                    if(type==0)
                      $("#_status").prop('checked', true);
                    form.render();
                },
                yes: function (layero, index) {
                    form.on('submit(formVerify)', function (data) {
                        let param = getparams(type, data.field);
                        saveData(url, param);
                        return false;
                    });
                }
                ,
                btn2: function (index, layero) {
                    layer.closeAll();
                },
                cancel: function (layero, index) {
                    layer.closeAll();
                }
            });
        }

        function searchForm() {
            layui.use('table', function () {
                let loginName = $("#loginName").val();
                let phonenumber = $("#phonenumber").val();
                let status = $("#status").val();
                let startTime = $("#startTime").val();
                let endTime = $("#endTime").val();
                if (startTime != "" && endTime != "") {
                    if (startTime > endTime) {
                        layer.msg('时间起始不可大于时间截止！');
                        $("#endTime").val("");
                        return;
                    }
                }
                let table = layui.table;
                table.reload('demoTable', {
                    where: {
                        loginName: loginName, phonenumber: phonenumber,
                        status: status, startTime: startTime,
                        endTime: endTime
                    }
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            });
        }
    });

    //让时间插件无法选中 达到禁止手输的目的
    function noInput(dom) {
        $(dom).blur();
    }

    function getparams(type, data) {
        //type==0 ==>新增 type==1 ==>编辑
        let o = {};
        o.userName = data.userName ? data.userName : null;
        o.phonenumber = data.phonenumber ? data.phonenumber : null;
        o.loginName = data.loginName ? data.loginName : null;
        if (type == 0)
            o.password = data.password ? data.password : null;
        else if (type == 1)
            o.userId = data.userId ? data.userId : null;
        o.email = data.email ? data.email : null;
        o.status = data.status ? 0 : 1;
        o.sex = data.sex;
        return o;
    }
</script>
<script type="text/html" id="bar">
    <a shiro:hasPermission="system:sysUser:edit" class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a shiro:hasPermission="system:sysUser:del" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a shiro:hasPermission="system:sysUser:reset" class="layui-btn layui-btn-warm layui-btn-xs" lay-event="reset">重置</a>
</script>
<script id="checkboxS" type="text/html">
    <!-- 这里的 checked 的状态只是演示 -->
    <input type="checkbox" value="{{d.userId}}" lay-skin="switch" lay-text="开启|停用" lay-filter="release" {{ d.status== 0
           ? 'checked' : '' }}>
</script>
</body>
